Vue.component('add-logistics', {//
    template: `<el-form ref="contract" :model="form" :rules="rules" :inline-message="true">
        <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="商品名称">
                <el-form-item prop="Article_Name">
                    <el-select v-model.trim="form.Sales_Order_Detail_SerialNumber" filterable clearable style="width: 100%;" placeholder="请选择商品">
                        <el-option v-for="item in data" :key="item.Sales_Order_Detail_SerialNumber" :label="item.Article_Name+'(规格:'+item.Specifications_Name+')'" :value="item.Sales_Order_Detail_SerialNumber"></el-option>
                    </el-select>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="物流公司">
                <el-form-item prop="Logistics_Code">
                    <el-select v-model.trim="form.Logistics_Code" filterable clearable style="width: 100%;" placeholder="请选择物流公司">
                        <el-option v-for="item in logistics" :key="item.Logistics_Code" :label="item.Logistics_Name" :value="item.Logistics_Code"></el-option>
                    </el-select>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="物流编号">
                <el-form-item prop="Logistics_Number">
                    <el-input v-model.trim="form.Logistics_Number" placeholder="请输入物流编号"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="发货数量">
                <el-form-item prop="Delivery_Quantity">
                    <el-input-number v-model="form.Delivery_Quantity" :min="1" :max="max"></el-input-number>
                    <span style="font-size: 12px;font-weight: 700;">需发货：{{obj.Quantity}}&nbsp;&nbsp;&nbsp;已发货：{{obj.Delivery_Quantity}}</span>
                </el-form-item>
            </el-descriptions-item>
        </el-descriptions>
    </el-form>`,
    props: ['form', 'data'],
    data() {
        return {
            rules: {},
            logistics: [],
        }
    },
    mounted() {
        this.getData();
    },
    computed: {
        obj() {
            let obj = this.data.filter(i => i.Sales_Order_Detail_SerialNumber == this.form.Sales_Order_Detail_SerialNumber)[0]
            return obj ? obj : { Quantity: 0, Delivery_Quantity: 0 };
        },
        max() {
            return accSub(this.obj.Quantity, this.obj.Delivery_Quantity)
        }
    },
    watch: {
        'form.Sales_Order_Detail_SerialNumber'(val) {
            let obj = this.data.filter(i => i.Sales_Order_Detail_SerialNumber == val)[0]
            this.form.Quantity = obj.Quantity
            this.form.Quantity1 = obj.Delivery_Quantity
        }
    },
    methods: {
        getData() {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'GET',
                data: {
                    Data: 'business_logistics_info',
                    Condition: "Row_Status='0'",
                },
                success: function (Result) {
                    that.logistics = Result;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
    },
})
Vue.component('show-detail', {//修改记录组件
    template: `<el-dialog title="订单详情" :visible.sync="visibleDialog" width="80vw">
        <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="1">
                <div class="table_titel">
                    <div class="titel">订单信息</div>
                </div>
                <el-descriptions id="show" :column="2" border size="small">
                    <el-descriptions-item label="订单编号">
                        <el-input v-model="data.Sales_Order_SerialNumber" :disabled="true"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="参与活动">
                        <el-input v-model="data.Activity_Name" :disabled="true"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="订单金额">
                        <el-input v-model="Amount" :disabled="true"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="积分比例">
                        <el-input v-model="Deduction_Ratio" :disabled="true"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="订单状态">
                        <el-input v-model="Row_Status" :disabled="true"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="备注">
                        <el-input v-model="data.Sales_Message" :disabled="true"></el-input>
                    </el-descriptions-item>
                </el-descriptions>
                <div class="table_titel">
                    <div class="titel">下单人信息</div>
                </div>
                <el-descriptions id="show" :column="2" border size="small">
                    <el-descriptions-item label="下单账户">
                        <el-input v-model="data.Member_Name" :disabled="true"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="下单时间">
                        <el-input v-model="data.Sales_Date" :disabled="true"></el-input>
                    </el-descriptions-item>
                </el-descriptions>
                <div class="table_titel">
                    <div class="titel">收货人信息</div>
                </div>
                <el-descriptions id="show" :column="2" border size="small">
                    <el-descriptions-item label="姓名">
                        <el-input v-model="data.Sales_Contacts" :disabled="true"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="手机号">
                        <el-input v-model="data.Sales_Phone" :disabled="true"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="地址">
                        <el-input v-model="Sales_Address" :disabled="true"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="详情地址">
                        <el-input v-model="Sales_Address_Detail" :disabled="true"></el-input>
                    </el-descriptions-item>
                </el-descriptions>
            </el-tab-pane>
            <el-tab-pane label="商品详情" name="2">
                <el-table :data="tableData" stripe border height="50vh">
                    <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                    <el-table-column align="center" prop="Supplier_Article_SerialNumber" label="供应商品编号"></el-table-column>
                    <el-table-column align="center" prop="Article_Name" label="商品名称"></el-table-column>
                    <el-table-column align="center" prop="Specifications_Name" label="规格名称"></el-table-column>
                    <el-table-column align="center" prop="Picture_URL" width="140" label="规格图片">
                        <template v-slot="{row}">
                            <el-image fit="contain" :preview-src-list="[BASE_IMG + row.Picture_URL]" :src="BASE_IMG + row.Picture_URL" style="width:100px;height: 100px;"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="Supplier_Name" label="供应商"></el-table-column>
                    <el-table-column align="center" prop="Sales_Unit_Price" label="商品单价"></el-table-column>
                    <el-table-column align="center" prop="Quantity" label="商品数量"></el-table-column>
                    <el-table-column align="center" prop="Amount" label="商品总价"></el-table-column>
                    <el-table-column align="center" width="100" label="特殊状态">
                        <template v-slot="{row}">
                            {{Refund(row)}}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作">
                        <template v-slot="{row}">
                            <el-button :type="isRefund(row)?'danger':'info'" :disabled="!isRefund(row)" size="small" @click="RefundRequest(row)">退款</el-button>
                            <!--<el-button :type="isRefund(row)?'danger':'info'" :disabled="!isRefund(row)" size="small" @click="RefundRequest(row)">换货</el-button>-->
                        </template>   
                    </el-table-column>
                </el-table>
                <el-pagination style="margin-top: 5px;" background @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" :current-page="form.page" :page-sizes="[10, 20, 30, 50]"
                    :page-size="form.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </el-tab-pane>
            <el-tab-pane label="发货信息" name="3">
                <el-table :data="tableData1" stripe border max-height="50vh" style="width: 100%">
                    <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                    <el-table-column align="center" prop="Article_Name" label="商品名称"></el-table-column>
                    <el-table-column align="center" prop="Supplier_Name" label="供应商名称"></el-table-column>
                    <el-table-column align="center" prop="Quantity" label="需发货量"></el-table-column>
                    <el-table-column align="center" prop="Delivery_Quantity" label="已发数量"></el-table-column>
                    <el-table-column align="center" label="未发数量">
                        <template v-slot="{row}">
                            {{parseInt(row.Quantity) - parseInt(row.Delivery_Quantity)}}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="发货状态">
                        <template v-slot="{row}">
                            <el-tag :type="row.Row_Status=='0'?'':row.Row_Status=='1'?'warning':'success'">{{Type(row.Row_Status)}}</el-tag>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="物流信息" name="4">
                <div class="table_titel">
                    <div></div>
                    <div class="operation">
                        <el-button type="primary" @click="Add" size="small">新增物流信息</el-button>
                    </div>
                </div>
                <el-table :data="tableData2" stripe border height="50vh" style="width: 100%">
                    <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                    <el-table-column align="center" show-overflow-tooltip prop="Sales_Order_Detail_SerialNumber" label="所属销售明细"></el-table-column>
                    <el-table-column align="center" show-overflow-tooltip prop="Logistics_Name" label="物流公司"></el-table-column>
                    <el-table-column align="center" show-overflow-tooltip prop="Supplier_Name" label="供应商"></el-table-column>
                    <el-table-column align="center" show-overflow-tooltip prop="Logistics_Number" label="物流单号">
                        <template v-slot="{row}">
                            <span style="cursor: pointer;" @click="handleLogistics(row.Logistics_Number)">{{row.Logistics_Number}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" show-overflow-tooltip prop="Delivery_Data" width="180" label="发货时间"></el-table-column>
                    <el-table-column align="center" show-overflow-tooltip prop="Article_Name" width="180" label="商品名称"></el-table-column>
                    <el-table-column align="center" show-overflow-tooltip prop="Specifications_Name" width="180" label="规格名称"></el-table-column>
                    <el-table-column align="center" show-overflow-tooltip prop="Delivery_Quantity" label="发货数量"></el-table-column>
                    <!-- <el-table-column width="100" align="center" label="操作">
                        <template v-slot="{row}">
                            <el-button size="text" @click="Edit(row)">编辑</el-button>
                        </template>
                    </el-table-column>-->
                </el-table>
            </el-tab-pane>
        </el-tabs>
        <span slot="footer" class="dialog-footer">
            <el-button @click="$emit('update:visible',false)">取消</el-button>
        </span>
    </el-dialog>`,
    props: ['data', 'visible'],
    data() {
        return {
            dialogVisible: false,
            visibleDialog: false,
            tableData: [],//详情
            tableData1: [],//发货信息
            tableData2: [],//物流信息
            activeName: '1',
            form: {
                SQLSerialNumber: "P_business_sales_order_detail",
                PaginationNumber: 1,
                RowAmount: 10,
                ExtensionCondition: '',
                Condition: '',
                Sales_Order_SerialNumber: '',
            },
            form1: {//添加
                Sales_Order_Logistics_SerialNumber: '',
                Sales_Order_Detail_SerialNumber: '',
                Logistics_Number: '',
                Logistics_Code: '',
                Delivery_Quantity: 1,
                Delivery_Data: '',
                Quantity: '',
                Quantity1: ''
            },
            form2: {//修改

            },
            total: 0,
            loading: false
        }
    },
    computed: {
        Amount() {
            let Sales_Point = this.data.Sales_Point == 0 ? '' : this.data.Sales_Point + '积分';
            let i = this.data.Sales_Point != 0 && this.data.Reality_Amount != 0 ? '+' : ''
            let Reality_Amount = this.data.Reality_Amount == 0 ? '' : this.data.Reality_Amount + '元'
            return Sales_Point + i + Reality_Amount
        },
        Deduction_Ratio() {
            return `1积分=${this.data.Deduction_Ratio}分`
        },
        Refund() {
            return function (row) {
                if (parseInt(row.Refunded_Quantity) == 0) {
                    if (row.Row_Status == '0') {
                        return "未发货";
                    } else if (row.Row_Status == '1') {
                        return "部分发货";
                    } else if (row.Row_Status == '2') {
                        return "已发货";
                    } else if (row.Row_Status == '3') {
                        return "签收";
                    } else if (row.Row_Status == '14') {
                        return "拒签";
                    } else if (row.Row_Status == '6') {
                        return "回退";
                    } else if (row.Row_Status == '4') {
                        return "退签";
                    } else {
                        return "";
                    }
                } else if (parseInt(row.Quantity) == parseInt(row.Refunded_Quantity)) {
                    return "已退款";
                } else if (parseInt(row.Refunded_Quantity) > 0) {
                    return "部分退款"
                }
            }
        },
        Type() {
            return function (str) {
                switch (str) {
                    case "0":
                        return "待发货";
                    case "1":
                        return "发货中";
                    case "2":
                        return "已发货";
                    default:
                        return ""
                }
            }
        },
        isRefund() {//是否允许退款
            return function (row) {
                if (row.Quantity == row.Refunded_Quantity) { //不允许退款
                    return false;
                } else {
                    if (this.data.Row_Status && (this.data.Row_Status.charAt(1) == '3' || this.data.Row_Status.charAt(1) == '4' || this.data.Row_Status.charAt(1) == '5')) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        },
        Row_Status() {
            if (this.data.Refund_Type == '1') {
                return "已退款";
            } else if (this.data.Refund_Type == '2') {
                return "部分退款";
            } else {
                let Row_Status = this.data.Row_Status ? this.data.Row_Status.charAt(1) : '';
                switch (Row_Status) {
                    case "0":
                        return "待付款";
                    case "1":
                        return "待付款";
                    case "2":
                        return "待付款";
                    case "3":
                        return "已付款";
                    case "4":
                        return "已发货";
                    case "5":
                        return "已完成";
                    case "6":
                        return "已取消";
                    case "7":
                        return "已取消";
                    default:
                        return ""
                }
            }
        },
        Sales_Address() {
            try {
                let strs = this.data.Sales_Address.split('/');
                return strs[0] + "-" + strs[1] + "-" + strs[2];
            } catch (error) {
                return ''
            }
        },
        Sales_Address_Detail() {
            try {
                return this.data.Sales_Address.split('/')[3]
            } catch (error) {
                return ''
            }
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible
        },
        visibleDialog(val) {
            this.$emit('update:visible', val)
        },
        'data.Sales_Order_SerialNumber': function (val) {
            this.form.Sales_Order_SerialNumber = val;
            this.tableData = [],//详情
            this.tableData1 = [],//发货信息
            this.tableData2 = [],//物流信息
            this.getList(this.form);
            this.getList1(val);
            this.getList2(val);
        }
    },
    methods: {
        handleSizeChange(val) {
            this.form.PaginationNumber = 1;
            this.form.RowAmount = val;
            this.getList(this.form)
        },
        handleCurrentChange(val) {
            this.form.PaginationNumber = val;
            this.getList(this.form)
        },
        Edit(row) {

        },
        Add() {
            const that = this;
            this.form1 = {//添加
                Sales_Order_Logistics_SerialNumber: '',
                Sales_Order_Detail_SerialNumber: '',
                Logistics_Number: '',
                Logistics_Code: '',
                Delivery_Quantity: 1,
                Delivery_Data: '',
                Quantity: ''
            };
            const h = this.$createElement;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data: {
                    SQLSerialNumber: 'A_business_sales_order_logistics',
                    Condition: window.btoa(unescape(encodeURIComponent(this.data.Sales_Order_SerialNumber))),
                    ExtensionCondition: ''
                },
                success: function (data) {
                    that.$msgbox({
                        title: '添加物流信息',
                        message: h('div', [
                            h('add-logistics', {
                                props: {
                                    form: that.form1,
                                    data,
                                }
                            })
                        ]),
                        customClass: 'logistics-message-box',
                        showCancelButton: true,
                        confirmButtonText: '确定',
                        beforeClose: (action, instance, done) => {
                            if (action === 'confirm') {
                                if(accAdd(that.form1.Delivery_Quantity,that.form1.Quantity1) > that.form1.Quantity) {
                                    that.$message({
                                        message: '该商品已全部发货,无法继续发货',
                                        type: 'warning'
                                    })
                                    return
                                }
                                instance.confirmButtonLoading = true; 
                                $.ajax({
                                    headers: requestHeaders(),
                                    url: `${BASE_URL2}/member/getMemberPoint`,
                                    type: 'POST',
                                    data: {
                                        Data: JSON.stringify([{
                                            tableName: 'business_sales_order',
                                            Condition: window.btoa(unescape(encodeURIComponent("Sales_Order_SerialNumber='" + that.data.Sales_Order_SerialNumber + "'"))),
                                        }, {
                                            tableName: 'business_sales_order_detail',
                                            Condition: window.btoa(unescape(encodeURIComponent("Sales_Order_Detail_SerialNumber='" + that.form1.Sales_Order_Detail_SerialNumber + "'"))),
                                        }]),
                                    },
                                    success: function ({ business_sales_order, business_sales_order_detail }) {
                                        if (business_sales_order.length == 1 && business_sales_order_detail.length == 1) {
                                            that.form1.Delivery_Data = getYMDHMSDate();
                                            that.form.Sales_Order_Detail_SerialNumber = that.form1.Sales_Order_Detail_SerialNumber;
                                            //修改销售订单状态
                                            let Status = business_sales_order[0].Row_Status.charAt(0);
                                            if (parseInt(that.form1.Quantity) == parseInt(that.form1.Delivery_Quantity) + parseInt(that.form1.Quantity1)) {
                                                business_sales_order[0].Row_Status = Status + '4'//发货中
                                                business_sales_order_detail[0].Row_Status = '2'//明细发货但没完成
                                            } else {
                                                business_sales_order_detail[0].Row_Status = '1'//明细发货完成
                                            }
                                            $.ajax({
                                                headers: requestHeaders(),
                                                url: `${BASE_URL2}/generalBusiness/generalSave`,
                                                type: 'POST',
                                                data: {
                                                    Data: JSON.stringify({
                                                        Add: { business_sales_order_logistics: [that.form1], base_operation_log: [generateLog('发货', '平台端操作', 'business_sales_order', JSON.stringify({ Modify: { business_sales_order, business_sales_order_detail }, Add: { business_sales_order_logistics: [that.form] } }))] },
                                                        Modify: { business_sales_order, business_sales_order_detail }
                                                    })
                                                },
                                                success: function (res) {
                                                    if (res.Status === 'success') {
                                                        //订阅快递100
                                                        $.ajax({
                                                            headers: requestHeaders(),
                                                            url: `${BASE_URL2}/waybill/subscribeWayBillState?Data=${that.form1.Logistics_Number}`,
                                                            type: 'GET',                                        
                                                            complete: function (XMLHttpRequest) {
                                                                instance.confirmButtonLoading = false;
                                                                that.$message.success("提交成功");
                                                                that.getList(that.form);
                                                                that.getList1(that.data.Sales_Order_SerialNumber);
                                                                that.getList2(that.data.Sales_Order_SerialNumber);
                                                                that.$emit('success');
                                                                done();
                                                                requestPretreatment(XMLHttpRequest);
                                                            },
                                                            dataType: "json"
                                                        })
                                                    } else {
                                                        that.$message.error("提交失败，请稍后再试")
                                                    }
                                                },
                                                complete: function (XMLHttpRequest) {
                                                    requestPretreatment(XMLHttpRequest);
                                                },
                                                dataType: "json"
                                            })
                                        } else {
                                            instance.confirmButtonLoading = false;
                                        }
                                    },
                                    complete: function (XMLHttpRequest) {
                                        requestPretreatment(XMLHttpRequest);
                                    },
                                    dataType: "json"
                                })

                            } else {
                                that.loading = false;
                                done();
                            }
                        }
                    }).then(() => { });
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        getList(form) {
            const that = this;
            let data = deepClone(form);
            data.Condition = window.btoa(unescape(encodeURIComponent(data.Sales_Order_SerialNumber)))
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
                type: 'POST',
                data,
                success: function (Result) {
                    that.tableData = Result.Rows;
                    that.total = Result.TotalRows;
                    console.log(Result);
                },
                complete: function (XMLHttpRequest) {
                    that.refreshDialog = false;
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        getList1(Sales_Order_SerialNumber) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data: {
                    SQLSerialNumber: 'P_business_sales_order_detail1',
                    Condition: window.btoa(unescape(encodeURIComponent("%" + Sales_Order_SerialNumber + "%,%" + Sales_Order_SerialNumber + "%"))),
                    ExtensionCondition: ''
                },
                success: function (Result) {
                    that.tableData1 = Result;
                },
                complete: function (XMLHttpRequest) {
                    that.refreshDialog = false;
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        getList2(Sales_Order_SerialNumber) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: 'POST',
                data: {
                    SQLSerialNumber: 'P_business_sales_order_logistics',
                    Condition: window.btoa(unescape(encodeURIComponent(Sales_Order_SerialNumber))),
                    ExtensionCondition: ''
                },
                success: function (Result) {
                    that.tableData2 = Result;
                },
                complete: function (XMLHttpRequest) {
                    that.refreshDialog = false;
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        handleLogistics(Data) {
            const that = this;
            const h = this.$createElement;
            $.ajax({
                url: `${BASE_URL1}/getWayBillStatus?grant_type=tourist`,
                type: 'GET',
                data: { Data },
                success: function (res) {
                    that.$msgbox({
                        title: '查看物流信息',
                        message: h('div', { style: { marginLeft: '-40px' } }, [
                            h('logistics', {
                                props: {
                                    data: res.message == 'ok' ? res.data : []
                                }
                            })
                        ]),
                        customClass: 'logistics-message-box',
                        showCancelButton: false,
                        confirmButtonText: '确定',
                    }).then(action => { });
                },
                dataType: "json"
            });
        },
        RefundRequest(row) {//退款申请
            if (row.Row_Status == '2') {
                this.$message.error("当前商品已发货，无法人工退款");
                return
            }
            const that = this;
            this.$confirm('警告！此操作将对该明细进行人工退款申请, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                $.ajax({
                    headers: requestHeaders(),
                    url: `${BASE_URL2}/collection/saveRefunds`,
                    type: 'POST',
                    data: {
                        Sales_Order_Detail_SerialNumber: row.Sales_Order_Detail_SerialNumber,
                        Refund_Type: '00',
                        Refund_Message: '管理员发起退款',
                        Refund_Quantity: row.Refundable_Quantity,
                        Refund_Cause: '管理员发起退款',
                        Refund_Explain: '仅退款',
                    },
                    success: function (Result) {
                        if (Result.Status == 'success') {
                            that.$message.success("已提交申请")
                            that.getList(that.form);
                        }
                    },
                    complete: function (XMLHttpRequest) {
                        that.refreshDialog = false;
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                });
            }).catch(() => { });
        }
    }
})